import { defineStore } from 'pinia'
import router from '@/router'
import { createStorage } from '@/utils/storage'
import { ACCESS_TOKEN } from '@/enums/cacheEnum'
import { useMenuStore } from './menu'

const Storage = createStorage()
const SessStorage = createStorage({
  storage: sessionStorage
})

export const useUserStore = defineStore('app-user', {
  state: () => ({
    token: Storage.get(ACCESS_TOKEN, ''),
    username: '',
    userInfo: null,
    permission: []
  }),
  actions: {
    /**
     * 设置token
     */
    setToken(info = '') {
      this.token = info
      Storage.set(ACCESS_TOKEN, info)
    },

    /**
     * 登录
     */
    handleLogin(data) {
      this.setToken(data + 'test')
    },

    /**
     * 清除登录状态, 不请求接口
     */
    handleClearLoginOut() {
      // 清除tabViews
      SessStorage.clear()

      // 清理菜单数据
      const menuStore = useMenuStore()
      menuStore.setMenu()

      this.setToken()
      router.push({
        path: '/login'
      })
    }
  }
})
